﻿using Common.Enums;
using Common.Helpers;
using Common.Services;
using Domain.Repositories;
using Domain.ValueObjects;

namespace Domain.Services;

#nullable disable

public class MenuDomainService : IScopedDependency
{
    private readonly IMenuRepository _repository;
    private readonly ISnowFlakeService _snowFlakeService;

    public MenuDomainService(
        IMenuRepository repository, ISnowFlakeService snowFlakeService)
    {
        _repository = repository;
        _snowFlakeService = snowFlakeService;
    }

    /// <summary>
    /// 收集接口信息
    /// </summary>
    /// <returns></returns>
    public IEnumerable<Menu> WebAPIEndpointCollectionForMenu()
    {
        var controllerInfos = WebApiDocHelper.GetWebApiControllersWithActions();
        var menus = new List<Menu>();
        foreach (var controllerInfo in controllerInfos)
        {
            var controllerMenu = new Menu
            {
                Id = _snowFlakeService.GenerateId(),
                Code = controllerInfo.ControllerName.ToLower(),
                Name = controllerInfo.ControllerDescription,
                Url = $"/api/{controllerInfo.ControllerName}".ToLower(),
                Meta = new Meta(MetaType.Menu, controllerInfo.ControllerDescription)
            };
            foreach (var actionInfo in controllerInfo.Actions)
            {
                var actionInfoMenu = new Menu();

                actionInfoMenu.Id = _snowFlakeService.GenerateId();
                actionInfoMenu.ParentId = controllerMenu.Id;
                actionInfoMenu.Name = actionInfo.Description;
                actionInfoMenu.HttpMethods = actionInfo.HttpMethods;
                actionInfoMenu.Meta = new Meta(MetaType.Button, actionInfoMenu.Name);
                if (actionInfo.Route != null)
                {
                    actionInfoMenu.Url = $"/api/{controllerInfo.ControllerName}/{actionInfo.Route}".ToLower();
                }
                else
                {
                    actionInfoMenu.Url = $"/api/{controllerInfo.ControllerName}".ToLower();
                }
                if (string.IsNullOrWhiteSpace(actionInfo?.Route))
                {
                    actionInfoMenu.Code = $"{controllerMenu.Code}:{actionInfo.ActionName.Replace("Async", "")}".ToLower();
                }
                else
                {
                    actionInfo.Route = (actionInfo?.Route?
                    .Replace("/", ":")
                    .Replace("{", "")
                    .Replace("}", "")
                    .Replace("?", ""))
                    .TrimEnd(':')
                    .ToLower();
                    actionInfoMenu.Code = $"{controllerMenu.Code}:{actionInfo.Route}";
                }

                menus.Add(actionInfoMenu);
            }
            menus.Add(controllerMenu);
        }
        return menus;
    }
}
